<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 采购基金
 */
namespace app\allwin\model;
use think\Model;
use util\Util;

class Fund extends Model
{
    protected $pk = 'id';
    protected $table = 'ai_allwin_fund';

    /**
     * 基金账户充值
     * @param integer $miniapp_id
     * @param integer $money(元)
     * @return void
     */
    public function recharge(int $miniapp_id,float $money){
        $info = self::where(['member_miniapp_id' => $miniapp_id])->find();
        if(empty($info)){
            $data['member_miniapp_id'] = $miniapp_id;
            $data['balance']           = floatval($money);
            $data['subsidize']         = 0;
            $data['subsidize_num']     = 0;
            return self::insert($data);
        }else{
            $info->balance = floatval($info->balance+$money);
            return $info->save();
        }
    }

    /**
     * 账务补贴
     * @param integer $miniapp_id
     * @param integer $money(元)
     * @return void
     */
    public function subsidy(int $miniapp_id,float $money){
        $rel = self::where(['member_miniapp_id' => $miniapp_id])->find();
        if(empty($rel)){
            return;
        }else{
            if($rel->balance <= 0){
                return;
            } 
            $subsidize = ($rel->balance-$money) < 0 ? $rel->balance : $money;
            $rel->balance       = ['dec',$subsidize];
            $rel->subsidize     = ['inc',$subsidize];
            $rel->subsidize_num = ['inc',1];
            $rel->save();
            return $subsidize;
        }
    }
}